package Servidor.Controlador;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import Servidor.Modelo.Games.Game;
import Servidor.Modelo.Games.GameList;

/**
 * This class creates a Thread for create a new game
 * @author Jorge Perez Martin
 */
class NewGameTask extends Thread implements OcaTask {

    Socket socket;
    BufferedReader read;
    PrintWriter write;

    public NewGameTask(Socket incoming, BufferedReader read, PrintWriter write) {
        this.socket = socket;
        this.read = read;
        this.write = write;
    }

    @Override
    public void executeTask() {
        this.start();
    }

    @Override
    public void run() {
        String idOwner = null;
        Game game = null;
        int idOwnerInt = 0;
        String nameGame = null;

        try {
            idOwner = read.readLine();
        } catch (IOException ex) {
            System.out.println("ID_OWNER INVALID");
        }

        try {
            nameGame = read.readLine();
        } catch (IOException ex) {
            System.out.println("NAME_GAME INVALID");
        }
        
        try {
            idOwnerInt = Integer.parseInt(idOwner);
            game = new Game(idOwnerInt, nameGame);
            //game.setId_owner(idOwnerInt);

        } catch (NumberFormatException e) {
            System.out.println("ID_OWNER INVALID");
        }

        write.println(game.getId_game());

        GameList.getInstance().add_game(game);
        new JoinGameTask(game.getId_game(), socket, read, write).executeTask();
    }
}
